package com.itheima.service.impl;

import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @author Encounter
 * @date 2024/10/10 15:13<br/>
 */
@Service
public class OrderSettingServiceImpl implements OrderSettingService
    {
        @Autowired
        private OrderSettingMapper orderSettingMapper;
        
        /**
         * 导出Excel
         *
         * @param filename 文件名
         * @param response 响应
         */
        @Override
        public void download(String filename, HttpServletResponse response)
            {
                // 设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                //获取要写入的数据
                List<OrderSetting> orderSettingList = orderSettingMapper.queryAll();
                
                try
                    {
                        //通过POI将数据写入Excel文件
                        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/" + filename);
                        if (in != null)
                            {
                                //基于模板创建一个Excel对象
                                XSSFWorkbook workbook = new XSSFWorkbook(in);
                                
                                //获取当前sheet页
                                XSSFSheet sheet = workbook.getSheetAt(0);
                                
                                //设置单元格格式，存入Date格式
                                XSSFCellStyle cellStyle = workbook.createCellStyle();
                                XSSFCreationHelper creationHelper = workbook.getCreationHelper();
                                cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd"));
                                //遍历集合开始插入数据
                                for (int i = 0; i < orderSettingList.size(); i++)
                                    {
                                        OrderSetting orderSetting = orderSettingList.get(i);
                                        //报表第一行有数据，从第二行开始插入
                                        XSSFRow row = sheet.createRow(i + 1);
                                        //在第一格插入时间
                                        XSSFCell cell = row.createCell(0);
                                        cell.setCellStyle(cellStyle);
                                        cell.setCellValue(orderSetting.getOrderDate());
                                        //在第二格插入可预约人数
                                        row.createCell(1).setCellValue(orderSetting.getNumber());
                                        //在第三格插入已预约人数
                                        //row.createCell(2).setCellValue(orderSetting.getReservations());
                                    }
                                //通过输出流将Excel文件下载到客户端浏览器
                                ServletOutputStream outputStream = response.getOutputStream();
                                workbook.write(outputStream);
                                
                                //关闭资源
                                outputStream.close();
                                workbook.close();
                                in.close();
                            }
                    }
                catch (Exception e)
                    {
                        throw new RuntimeException(e);
                    }
                
            }
        
        /**
         * 文件上传
         *
         * @param excelFile Excel 文件
         */
        @Override
        public void upload(MultipartFile excelFile)
            {
                try (InputStream in = excelFile.getInputStream();
                     XSSFWorkbook excel = new XSSFWorkbook(in))
                    {
                        //获取第一个sheet页
                        XSSFSheet sheet = excel.getSheetAt(0);
                        //获取当前页总行数
                        int countOfRows = sheet.getPhysicalNumberOfRows();
                        //遍历每一行开始操作，第一行为表头，直接跳过
                        for (int rowNum = 1; rowNum < countOfRows; rowNum++)
                            {
                                XSSFRow row = sheet.getRow(rowNum);
                                if (row == null)
                                    {
                                        //当前行为空，跳过，直接开始下一行
                                        break;
                                    }
                                //获取第一格信息
                                Date orderDate = row.getCell(0).getDateCellValue();
                                //获取第二格信息
                                int number = (int) row.getCell(1).getNumericCellValue();
                                //封装获取到的信息
                                OrderSetting orderSettingUpdate = new OrderSetting();
                                orderSettingUpdate.setOrderDate(orderDate);
                                orderSettingUpdate.setNumber(number);
                                
                                //查询数据表中是否存在该条数据
                                OrderSetting orderSetting = orderSettingMapper.queryByOrderDate(orderDate);
                                if (orderSetting == null)
                                    {
                                        //不存在，直接新增
                                        orderSettingMapper.insert(orderSettingUpdate);
                                    }
                                else if (number != orderSetting.getNumber())
                                    {
                                        //已有数据且新数据与原数据有差异，修改原数据
                                        orderSettingMapper.update(orderSettingUpdate);
                                    }
                            }
                    }
                catch (IOException e)
                    {
                        throw new RuntimeException(e);
                    }
            }
        
        /**
         * 订单设置修改
         *
         * @param orderSetting 订单设置
         * @return int 修改成功条数
         */
        @Override
        public int update(OrderSetting orderSetting)
            {
                return orderSettingMapper.update(orderSetting);
            }
        
        /**
         * 按月获取订单设置
         *
         * @param month 月
         * @return {@link List }<{@link OrderSetting }>
         */
        @Override
        public List<OrderSetting> getOrderSettingByMonth(String month)
            {
                List<OrderSetting> orderSettingList = orderSettingMapper.getOrderSettingByMonth(month);
                return orderSettingList;
            }
    }
